<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>演示分页算法</title>
		<style type="text/css">
			#paged li{
				float: left;
				list-style: none;
				border: #0000FF solid 1px;
				margin-right: 5px;
			}
			.current{
				background-color: red;
			}
		</style>
	</head>
	<body>
		
		<ul id="dataBox">
		</ul>
		<ul id="paged"></ul>
		<script type="text/javascript">
			var data_list = []
			
			for(var i=0; i<1000; i++){
				var obj = {"title": "title" + i, "new_id": "id" + i};
				data_list.push(obj)
			}
			
			// 当前页数,从1开始,
			var page = 1;
			// 每页数据条数
			var page_size = 100;
			// 数据总数
			var data_length = data_list.length;
			// 计算总页数的算法
			var page_num = Math.ceil(data_length / page_size);

			function selectPage(p){
				page = p;
				
				// 计算当前页面数据的起始索引(下标)
				var start_index = page_size * (page - 1);
				// 计算当前页面数据的结束下标
				var end_index = start_index + page_size;
				
				// 得到当前页面数据
				var result = data_list.slice(start_index, end_index)
				// console.log(result);
				var html = "";
				for(var i=0; i<result.length; i++){
				    html += "<li>";
					html += "new_id=" + result[i].new_id + ", title=" + result[i].title;
					html += "</li>"
				}
				document.getElementById('dataBox').innerHTML = html;
				
				var paged_html = ""
				for(var i=1; i<=page_num; i++){
					if(i == page){
						paged_html += "<li class='current'>"
					}else{
						paged_html += "<li onclick='selectPage(" + i + ")'>";
					}
					paged_html += i;
					paged_html += "</li>";
				}
				document.getElementById('paged').innerHTML = paged_html;
				// var data_length =  page * page_size
			}
			selectPage(1)
		</script>
		
	</body>
</html>
